﻿package rob.core{
	import flash.display.Sprite;
	import rob.parser.ParserOBJ;
	import rob.data.*;
	import rob.maths.*;
	import rob.skin.*;

	public class Poly3d extends Sprite{
		// different list of vertices for draw order (important for Gouraud)
		private var _aVertex:Array, _aVDraw:Array;
		private var _aUVCoord:Array;
		private var _material:Material;
		private var _skin;
		private var _vertNum:uint;
		private var _normal:Vect3d;
		private var _textured:Boolean, _gouraud:Boolean;
		private var _lineWeights:Array;
		
		public function Poly3d(matName:String, verts:Array, uvCoords:Array):void{
			_material = ParserOBJ.instance.getMaterialByName(matName);
			//_material = new Material("default",false,false,new RGB(200,200,200));
			
			_aVertex = verts;
			_aVDraw = _aVertex.slice();
			_aUVCoord = uvCoords;
			_lineWeights = [];
			_vertNum = _aVertex.length;
			updateNormal();
			
			//this.cacheAsBitmap = true;
			
			// choose skin
			_textured = _material.textured;
			_gouraud = _material.gouraud;
			if(_textured){
				_skin = new TextureSkin(matName,_aUVCoord,_aVertex);
			}
			else if(_gouraud){
				_skin = new GouraudSkin(_aUVCoord,_aVDraw);
			}
			else{
				_skin = new ColourSkin(_material.colour);
				_skin.applyLight(_normal);
			}
			
		}

		public function updateNormal():void{
			_normal = VectorMaths.cp(VectorMaths.sub(_aVertex[1],_aVertex[0]),
									VectorMaths.sub(_aVertex[2],_aVertex[0]));
			VectorMaths.normalise(_normal);
		}
		
		public function render():void{
			var l:uint = 0;
			
			with(this.graphics){
				clear();
				_skin.beginFill(this);
				lineStyle(0,0,_lineWeights[0]);
				moveTo(_aVDraw[0].sx,_aVDraw[0].sy);
				while(++l < _vertNum){
					lineTo(_aVDraw[l].sx,_aVDraw[l].sy);
					lineStyle(0,0,_lineWeights[l]);
				}
				endFill();
			}
		}
		
		public function setLineWeights(lws:Array):void{
			_lineWeights = lws.slice();
		}
		
		public function setupSkin():void{
			_skin.setup(_lineWeights);
		}
		
		public function get zdepth(){
			//var d:Number = (_aVertex[0].wz+_aVertex[1].wz+_aVertex[2].wz);
			//var d:Number = Math.max(Math.max(_aVertex[0].cd,_aVertex[1].cd),_aVertex[2].cd);
			var d:Number = (_aVertex[0].cd + _aVertex[1].cd + _aVertex[2].cd);
			return d;
		}
		
		public function get lineWeights():Array{ return _lineWeights;}
		public function get normal():Vect3d{return _normal;}
		public function get aVertex():Array{return _aVertex;}
		public function get aVDraw():Array{return _aVDraw;}
		public function get p0():Vert3d{return _aVertex[0];}
		public function get gouraud():Boolean{ return _gouraud;}
		
		public function clear(){
			this.graphics.clear();
		}
	
		override public function toString():String{
			return "Poly3d: {"+_material+"}";
		}

	}
}